#include"SeqList.h"

void test01()
{
    SL sl;//创建一个结构体
    SLInit(&sl);//初始化该结构体，结构体本身不属于指针而属于值，所以要取地址
    //具备了一个空的顺序表
    SLPushBack(&sl,1);
    SLPushBack(&sl,2);
    SLPushBack(&sl,3);
    SLPushBack(&sl,4);
    SLPrint(&sl);
    SLPushBack(&sl,5);
    SLPrint(&sl);
    SLPopFront(&sl);
    SLPrint(&sl);
    SLPopBack(&sl);
    SLPrint(&sl);
    SLPushFront(&sl,10);
    SLPrint(&sl);
}

void SLInit(SL* ps)//顺序表的初始化
{
    ps->arr = NULL;//指向空,也可以给空间，写成ps->arr = (SLTDataType*)malloc(sizeof(SLTDataType)*4);
    ps->size = ps->capacity = 0; 
}

int main()
{
    test01();
    return 0;
}

void SLCheckCapacity(SL* ps)
{
    //空间不够
    if(ps->size == ps->capacity)
    {
         int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
        //增容
        SLTDataType* tmp = (SLTDataType*)realloc(ps->arr , sizeof(SLTDataType) * newcapacity);
        if(tmp == NULL)
        {
            perror("realloc fail!");
            exit(1);
        }
        ps->arr = tmp;
        ps->capacity = newcapacity;
    }
}

//尾插
void SLPushBack(SL* ps,SLTDataType x)
{
    //检查空间是否足够
    SLCheckCapacity(ps);
    //空间足够
    ps->arr[ps->size++] = x;
}

//头插
void SLPushFront(SL* ps,SLTDataType x)
{
    //检查空间是否足够
    SLCheckCapacity(ps);
    //空间足够
    for(int i = ps->size;i>0;i--)
    {
        ps->arr[i] = ps->arr[i-1];
    }
    ps->arr[0] = x;
    ps->size++;
}

//尾删
void SLPopBack(SL* ps)
{
    assert(ps->size > 0);//确保顺序表中有数据
    ps->size--;
}

//头删
void SLPopFront(SL* ps)
{
    assert(ps->size>0);
    for(int i = 0;i < ps->size-1;i++)
    {
        ps->arr[i]=ps->arr[i+1];
    }
    ps->size--;
}

//打印
void SLPrint(SL* ps)
{
    for(int i = 0;i < ps->size;i++)
    {
        printf("%d ",ps->arr[i]);
    }
    printf("\n");
}

//查找,返回下标
int SLFind(SL* ps,SLTDataType x)
{
    for(int i = 0;i < ps->size; i++)
    {
        if(ps->arr[i] == x)
        {
            printf("Find it! The location is %d\n",i);
            return i;
        }
    }
    printf("Not Find!\n");
}

//中间pos处插入
void SLInsert(SL* ps,int pos,SLTDataType x)
{
    assert(pos >= 0 && pos <= ps->size );
    SLCheckCapacity(ps);
    for(int i = ps->size; i >pos;i--)
    {
        ps->arr[i]=ps->arr[i-1];
    }
    ps->arr[pos] = x;
    ps->size++;
}

//删除pos位置数据
void SLErase(SL* ps,int pos)
{
    assert(pos>=0 && pos<ps->size);
    for(int i = pos;i<ps->size-1;i++)
    {
        ps->arr[i]=ps->arr[i+1];
    }
    ps->size--;
}

//销毁
void SeqListDsetory(SL* ps)
{
    free(ps->arr);
    ps->arr=NULL;
    ps->size=ps->capacity=0;
}